package com.cuckoo.cuckoo_app2.ui;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.cuckoo.cuckoo_app2.MyApplication;
import com.cuckoo.cuckoo_app2.R;
import com.cuckoo.cuckoo_app2.apiAsync.BaseCallbac;
import com.cuckoo.cuckoo_app2.apiAsync.Imp.PlatformApiImp;
import com.cuckoo.cuckoo_app2.apiAsync.PlatformApi;
import com.cuckoo.cuckoo_app2.business.Imp.PlatformBusinessImp;
import com.cuckoo.cuckoo_app2.business.Imp.SiteLinkBusinessImp;
import com.cuckoo.cuckoo_app2.business.PlatformBusiness;
import com.cuckoo.cuckoo_app2.business.SiteLinkBusiness;
import com.cuckoo.cuckoo_app2.dao.Platform;
import com.cuckoo.cuckoo_app2.dao.SiteLink;
import com.cuckoo.cuckoo_app2.enums.TokneTypeEnum;
import com.cuckoo.cuckoo_app2.model.IntentResponseModel;
import com.cuckoo.cuckoo_app2.utils.DialogUtils;
import com.cuckoo.cuckoo_app2.utils.JavaScroptParameterUtils;
import com.cuckoo.cuckoo_app2.utils.LocalBroadCodeUtils;
import com.cuckoo.cuckoo_app2.utils.RouteUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;

import java.util.HashMap;
import java.util.Map;

public class WebViewActivity extends AppCompatActivity {

    private String ID;
    private String TYPE; // login  enter
    private WebView webView;
    private String webViewUrl;
    private SiteLink siteLink;
    private Platform platform;
    private Gson gson;
    private Context context;
    private PlatformBusiness platformBusiness = new PlatformBusinessImp();
    private SiteLinkBusiness siteLinkBusiness = new SiteLinkBusinessImp();
    private PlatformApi platformApi = new PlatformApiImp();
    private ValueCallback<Uri[]> mUploadMessage;
    private final int FILECHOOSER_RESULTCODE = 1;
    private boolean isPageLoaded = false;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;
        Log.i("TEST", "WebViewActivity.onCreate");
        setContentView(R.layout.activity_web_view);

        gson = new Gson();
        getSupportActionBar().hide();

        TextView title = findViewById(R.id.title);
        ImageView close = findViewById(R.id.close);

        Intent intent = getIntent();
        ID = intent.getStringExtra("id");
        TYPE = intent.getStringExtra("type");

        if (ID.equals(null) || ID.equals("")) {
            return;
        }

        siteLink = siteLinkBusiness.getByID(ID);
        if (siteLink == null) {
            return;
        }

        platform = platformBusiness.getById(ID);
        if (platform == null) {
            return;
        }

        title.setText(platform.getTitle());

        webView = findViewById(R.id.webview);
        // 启用JavaScript
        WebSettings webSettings = webView.getSettings();
        // 启用JavaScript
        webSettings.setJavaScriptEnabled(true);
        // 启用DOM存储
        webSettings.setDomStorageEnabled(true);
        // 启用内置缩放控件
        webSettings.setBuiltInZoomControls(false);
        // 设置页面自适应
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        // 设置缓存模式
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        // 设置字体大小和编码
        webSettings.setDefaultFontSize(16); // 设置默认字体大小，默认为16
        webSettings.setDefaultTextEncodingName("utf-8"); // 设置解码html页面时使用的默认文本编码名称

        // 插入参数
        Map<String, String> bodyMap = new HashMap<>();
        bodyMap.put("token", platform.getToken());
        bodyMap.put("localStorage", platform.getLocalStorage());

        // 添加JavaScriptInterface
        webView.addJavascriptInterface(new JavaScroptParameterUtils(bodyMap), "Android");

        // 设置WebViewClient
        webView.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                Log.i("TEST", "WebView.url:" + url);
                webViewUrl = url;

                // 进入网页前 执行代码
                if (!isPageLoaded) {
                    webView.evaluateJavascript(siteLink.getHomeCodeBefore(), null);

                    // 执行你的操作
                    isPageLoaded = true;
                    return;
                }

            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });

        webView.setWebChromeClient(new WebChromeClient() {
            // 用于Android 5.0+系统处理文件选择
            @Override
            public boolean onShowFileChooser(
                    WebView webView, ValueCallback<Uri[]> filePathCallback,
                    WebChromeClient.FileChooserParams fileChooserParams) {
                // 确保没有挂起的文件选择器消息
                if (mUploadMessage != null) {
                    mUploadMessage.onReceiveValue(null);
                }

                mUploadMessage = filePathCallback;

                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                intent.setType("image/*"); // 限制为图片

                // 启动ActivityForResult来让用户选择文件
                startActivityForResult(intent, FILECHOOSER_RESULTCODE);
                return true;
            }

        });

        setCookie(siteLink.getHomeUrl(), platform.getCookie());
        // 加载网页
        if (TYPE.equals("login")) {
            webView.loadUrl(siteLink.getLoginUrl());
        } else {
            webView.loadUrl(siteLink.getHomeUrl());
        }

        // 退出按钮
        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    // 注意：从 Android Lollipop（API 级别 21）开始，CookieSyncManager 已被弃用。
    // 在 Android Lollipop 及以上版本中，CookieManager 会自动同步 cookie，无需额外调用 sync 方法。
    public void setCookie(String url, String cookieValue) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            CookieSyncManager.createInstance(this);
        }

        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.removeSessionCookie(); // 如果需要，可以移除会话 cookie
        cookieManager.setCookie(url, cookieValue);

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            CookieSyncManager.getInstance().sync();
        }
    }

    // 保存token 只有 local    cookie 更新  api 不更新
    public void editStart(String token) {
        if (token.equals("") || token.equals("null")) {
            platform.setToken("");
            platform.setIsLogin(0);
            platform.setStart(0);
        } else {
            platform.setToken(token);
            platform.setIsLogin(1);
        }
    }

    // 同步云
    public void syncCloud() {
        platformBusiness.updata(platform);
        platformApi.PlatformEditAsync(platform, new BaseCallbac<JsonObject>() {
            @Override
            public void onSuccess(JsonObject data) {

            }

            @Override
            public void onFailure(String errorMessage) {

            }
        });

        // 通知页面 刷新
        LocalBroadCodeUtils.sendLocalBroadcast(context,
                LocalBroadCodeUtils.LOCAL_BROADCAST_TASK_REFRESH,
                new IntentResponseModel(LocalBroadCodeUtils.LOCAL_BROADCAST_TASK_REFRESH, null)
        );
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.i("TEST", "WebViewActivity.onStart");
        // 检测登录
        if (MyApplication.getInstances().getUser() == null) {
            RouteUtils.toLoginActivity(this);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.i("TEST", "WebViewActivity.onStop()");
        // 退出页面
        finishPage();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i("TEST", "WebViewActivity.onDestroy");

        if (webView != null) {
            webView.destroy();
        }
    }

    // 退出页面
    public void finishPage() {
        // 获取到token
        if (siteLink.getTokneType().equals(TokneTypeEnum.TOKEN_TYPE_COOKIE)) {
            String cookies = CookieManager.getInstance().getCookie(webViewUrl);
            if (cookies == null) {
                return;
            }
            // 保存
            editStart(cookies);
            // 同步云
            syncCloud();
        } else if (siteLink.getTokneType().equals(TokneTypeEnum.TOKEN_TYPE_LOCAL)) {
            // 页面加载完成后，可以在这里执行一些操作，但token已经在页面加载前通过JavaScriptInterface可用
            webView.evaluateJavascript(siteLink.getLoginCodeAfter(), new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String s) {
                    if (s == null || s.equals("") || s.equals("null")) {
                        return;
                    }
                    Log.d("WebView", "JavaScript Token: " + s);
                    String token = s.replaceAll("^\"|\"$", ""); // 去除字符串两端的引号
                    Log.i("WebView", "token: " + token);
                    // 保存
                    editStart(token);
                    // 同步云
                    syncCloud();
                }
            });
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode == FILECHOOSER_RESULTCODE) {
            if (null == mUploadMessage) return;

            Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();

            // 处理单文件选择（如果需要处理多文件，请修改此处）
            mUploadMessage.onReceiveValue(result != null ? new Uri[]{result} : null);
            mUploadMessage = null;
        }
    }

}
